package com.jzx.provider;

import com.jzx.provider.ucenter.UcenterService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author daihuihui
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UcenterService userService;

    /**
     * 进入controller层之前拦截请求
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String token = httpServletRequest.getHeader("token");
        String platform = httpServletRequest.getHeader("platform");
        if (StringUtils.isEmpty(token)) {
            httpServletResponse.setContentType("application/json");
            PrintWriter printWriter = httpServletResponse.getWriter();
            printWriter.write("{\"status\":\"205\",\"message\":\"USER_NOT_LOGIN\"}");
            printWriter.flush();
            printWriter.close();
            return false;
        }
        //判断登陆是否合法，并刷新token过期时间
        userService.isLogin(token,platform);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}